<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>test</title>
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.css" rel="stylesheet" type="text/css" />
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
        integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <style type="text/css">
        body {
            padding-top: 70px;
        }
    </style>
    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"
        integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
        crossorigin="anonymous"></script>
    <script>

        if (!String.prototype.format) {
            String.prototype.format = function () {
                var str = this.toString();
                if (!arguments.length)
                    return str;
                var args = typeof arguments[0],
                    args = (("string" == args || "number" == args) ? arguments : arguments[0]);
                for (arg in args)
                    str = str.replace(RegExp("\\{" + arg + "\\}", "gi"), args[arg]);
                return str;
            }
        }

        function init() {
            // 创建节点对象
            nodes = new vis.DataSet([]);
            // 创建连线对象
            edges = new vis.DataSet([]);
            // 创建一个网络拓扑图  不要使用jquery获取元素
            var container = document.getElementById('network_id');
            var data = { nodes: nodes, edges: edges };
            //全局设置，每个节点和关系的属性会覆盖全局设置
            var options = {
                autoResize: true,
                height: '100%',
                width: '100%',
                locale: 'en',
                clickToUse: false,
                // 设置关系连线
                edges: {
                    font: {
                        face: 'Microsoft YaHei'
                    },
                    length: 200
                },
                groups: {
                    useDefaultGroups: true,
                    Article: {
                        shape: 'box',
                        widthConstraint: 150,
                        color: {
                            border: 'black',
                            background: 'AliceBlue'
                        },
                        font: {
                            face: 'Microsoft YaHei'
                        }
                    },
                    Vegetable: {
                        shape: 'ellipse',
                        size: 15,
                        color: 'green',
                        font: {
                            face: 'Microsoft YaHei',
                            color: 'white'
                        }
                    },
                    City: {
                        shape: 'ellipse',
                        size: 15,
                        color: 'orange',
                        font: {
                            face: 'Microsoft YaHei'
                        }
                    },
                    Event: {
                        shape: 'star',
                        widthConstraint: 150,
                        color: {
                            border: 'black',
                            background: 'AliceBlue'
                        },
                        font: {
                            face: 'Microsoft YaHei'
                        }
                    },
                },
                //设置节点的相互作用
                interaction: {
                    //鼠标经过改变样式
                    hover: true
                    //设置禁止缩放
                    //zoomView:false
                },
                //力导向图效果
                physics: {
                    enabled: true,
                    barnesHut: {
                        gravitationalConstant: -4000,
                        centralGravity: 0.3,
                        springLength: 120,
                        springConstant: 0.04,
                        damping: 0.09,
                        avoidOverlap: 0
                    }
                }
            };
            network = new vis.Network(container, data, options);
            // network.on('beforeDrawing', function (context) {
            //     if (drawing) {
            //         return;
            //     }
            //     drawGrid(context)
            // })
            // // 下面2个事件，是为了减少我的自定义作图函数的调用次数，提升网页性能
            network.on('dragStart', function () {
                drawing = true;
            });
	
	    network.on("dragEnd", function(params){
	    	if (params.nodes&&params.nodes.length > 0){
		    network.clustering.updateClusteredNode(params.nodes[0], {physics : false});
		}
	    });
            // network.on('click', function () {
            //     alert('ok');
            //     network.editNode();
            // })
            // network.on("dragEnd", function (params) {
            //     alert('ok');
            //     if (params.nodes && params.nodes.length > 0) {
            //         network.clustering.updateClusteredNode(params.nodes[0], { physics: false });
            //     }
            // });
            network.on("doubleClick", function (params) {//双击事件
                if (params.nodes.length != 0) {

                    //获取需要的参数，获取参数后可到后台获取扩展后的数据
                    var node = network.body.data.nodes._data[params.nodes[0]];
                    console.log(node);
                    $("#details").find("tbody").empty();
                    exceptList = ['id', 'group', 'color'];
                    for (var k in node) {
                        console.log(k);
                        if (exceptList.indexOf(k) >= 0)
                            continue;
                        var v = node[k];
                        if (k == 'url') {
                            k = '原文链接';
                            v = "<a href = '" + v + "' target ='_blank'>原文链接</a>";
                        }
                        console.log(v);
                        let content = "<tr><td>" + k + "</td><td>" + v + "</td></tr>";
                        // console.log(content);
                        $("#details").find("tbody").append(content);
                    }

                }
            });
        }
        //扩展节点 param nodes和relation集合
        function createNetwork(param) {
            //添加节点
            var stdNodes = param.v;
            for (i in stdNodes) {
                var node = stdNodes[i];
                //除了固定的参数外，可以自己增加额外的参数
                nodes.add({
                    id: node.id,
                    label: node.name,
                    group: node.label
                });
            }
            var stdNodes = param.c;
            for (i in stdNodes) {
                var node = stdNodes[i];
                //除了固定的参数外，可以自己增加额外的参数
                nodes.add({
                    id: node.id,
                    label: node.name,
                    group: node.label

                });
            }
            var stdNodes = param.e;
            for (i in stdNodes) {
                var node = stdNodes[i];
                //除了固定的参数外，可以自己增加额外的参数
                nodes.add({
                    id: node.id,
                    title: node.type,
                    group: node.label,
                    label: node.name
                });
            }
            var stdNodes = param.a;
            for (i in stdNodes) {
                var node = stdNodes[i];
                //除了固定的参数外，可以自己增加额外的参数
                var tcolor = 'white'
                if (node.priceSenti == '正向')
                    tcolor = 'green'
                else if (node.priceSenti == '负向')
                    tcolor = 'red'
                nodes.add({
                    id: node.id,
                    title: node.text,
                    label: node.title,
                    group: node.label,
                    priceSenti: node.priceSenti,
                    indicator: node.indicator,
                    date: node.date,
                    url: node.url,
                    color: { background: tcolor }
                });
            }
            //添加关系
            cols = ['ra', 'rv', 'rc']
            for (i in cols) {
                stdEdges = param[cols[i]];
                for (j in stdEdges) {
                    var edge = stdEdges[j];
                    edges.add({
                        id: edge.id,
                        arrows: 'to',
                        from: edge.start_node,
                        to: edge.end_node,
                        label: edge.type,
                        font: { align: "middle" },
                    });
                }
            }

        }
        //拓扑
        var network;
        // 创建节点对象
        var nodes;
        // 创建连线对象
        var edges;

        //窗口加载事件
        $(function () {
            init();
            //修改初始缩放
            // network.moveTo({ scale: 1 });
            $("button#submit").click(function () {
                var question = $("#question").val();
                // console.log(question)

                var url = encodeURI("ques/answer?q=" + question);

                // console.log(url);
                $.ajax({
                    url: url,
                    async: false,
                    type: 'GET',
                    success: function (data, status) {
                        if (data['msg']) {
                            alert(data['msg']);
                        }
                        else if (status == "success") {
                            //alert('成功');
                            init();
                            createNetwork(data);
                            $('#prices').find('tbody').empty();
                            console.log(data.price);
                            for (i in data.price.price) {
                                let content = "<tr><td>" + data.price.date[i] + "</td><td>" + data.price.price[i] + "</td></tr>";
                                $('#prices').find('tbody').append(content);
                            }
                        }

                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(XMLHttpRequest.readyState + XMLHttpRequest.status + XMLHttpRequest.responseText);
                    }
                });

            });
            //结点隐藏
            $('input[type=checkbox][name=priceSenti]').change(function (e) {
                for (var i in network.body.data.nodes._data) {
                    if (i == 1)
                        console.log(network.body.data.nodes._data[i].priceSenti);
                    console.log(e.target.value);
                    if (network.body.data.nodes._data[i].priceSenti == e.target.value && !e.currentTarget.checked) {
                        network.clustering.updateClusteredNode(i, { hidden: true });
                    } else {
                        network.clustering.updateClusteredNode(i, { hidden: false });
                    }
                }
            });
            $('input[type=checkbox][name=indicator]').change(function (e) {
                for (var i in network.body.data.nodes._data) {
                    if (network.body.data.nodes._data[i].indicator == e.target.value && !e.currentTarget.checked) {
                        network.clustering.updateClusteredNode(i, { hidden: true });
                    } else {
                        network.clustering.updateClusteredNode(i, { hidden: false });
                    }
                }
            });

            //提交问题事件异步加载
        });

    </script>

</head>

<body>
    <div class="container-fluid">
        <nav class="navbar navbar-default navbar-fixed-top">
            <div class="container">
                <ul class="nav nav-tabs">
                    <li role="presentation" class="active"><a href="#">问答</a></li>
                    <li role="presentation"><a href="/crawler">手动采集</a></li>
                </ul>
            </div>
        </nav>
        <div class="row" style="height: 100%;">
            <div class="col-md-10">
                <div class="row" style="height: 50px; align-content: center;">
                    <div class="col-md-3"></div>
                    <div class="col-md-6">
                        显示节点
                        <input type="checkbox" name="priceSenti" checked value="正向" />正向
                        <input type="checkbox" name="priceSenti" checked value="负向" />负向
                        <input type="checkbox" name="indicator" checked value="供给" />供给
                        <input type="checkbox" name="indicator" checked value="需求" />需求
                        <input type="checkbox" name="indicator" checked value="自然环境" />自然环境
                        <input type="text" id="question" placeholder="输入问题" />
                        <button type="submit" id="submit">点击提交</button>
                    </div>
                    <div class="col-md-3"></div>
                </div>

                <div style="height: 1000px;" id="network_id" class="network"></div>
                <!-- 拓扑图容器-->
            </div>
            <div class="col-md-2">
                <div style="height: 500px;" class="row">
                    <table id='details' class="table table-hover">
                        <caption>节点详情</caption>
                        <thead>
                            <th>属性</th>
                            <th>值</th>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
                <div style="height: 400px;" class="row">
                    <table id='prices' class="table table-hover">
                        <caption>报价</caption>
                        <thead>
                            <th>日期</th>
                            <th>价格</th>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div>

    </div>
    <div></div>
    <div></div>

</body>

</html>
